package com.example.yjh_login.activitys;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import androidx.core.app.ActivityCompat;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.example.lib_mvp.TipUiDialog;
import com.example.lib_mvp.arouter.RouterUtils;
import com.example.lib_mvp.arouter.path.ArouterPath;
import com.example.lib_mvp.base.mvp.BaseMvpActivity;
import com.example.lib_mvp.httpUtil.HttpUrl;
import com.example.yjh_login.beans.HdLoginBean;
import com.example.yjh_login.jgServices.JPushUtils;
import com.example.yjh_login.presenterImp.LoginPresenter;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.tjf.lib_network.SpSaveUtils;
import com.tjf.lib_utils.LogsUtils;
import com.tjf.lib_utils.bean.BusEvent;

@Route(path = ArouterPath.PATH_LOGIN_LOGIN)
public class LoginActivity extends BaseMvpActivity<LoginPresenter> {

    JPushUtils jPushUtils;

    @Override
    protected int getLayoutId() {
        return 0;
    }

    @Override
    protected void initView() {
        super.initView();
        checkPage();
    }


    public void checkPage() {
        jPushUtils = new JPushUtils(this);
//        loginCheckReadBox.setChecked(SpSaveUtils.isShowPrivacy());
        if (!TextUtils.isEmpty(SpSaveUtils.getToken())) {
            Bundle extras = getIntent().getExtras();
            LogsUtils.i("测试==" + extras);
            if (extras != null) {
                if (extras.getInt("authOrder") == 1) {
                    LogsUtils.i("测试==+authOrder");
                    checkPermission();
                    return;
                }
                if (TextUtils.isEmpty(SpSaveUtils.getActivation()) || "0".equals(SpSaveUtils.getActivation())) {
                    startActivity(AuthOrderActivity.class);
                    finish();
                    return;
                }
                RouterUtils.navigate(ArouterPath.PATH_APP_MAIN_ACTIVITY);
                finish();
            } else {
                if (TextUtils.isEmpty(SpSaveUtils.getActivation()) || "0".equals(SpSaveUtils.getActivation())) {
                    startActivity(AuthOrderActivity.class);
                    finish();
                    return;
                }
                if ("1".equals(SpSaveUtils.getActivation())) {
                    RouterUtils.navigate(ArouterPath.PATH_APP_MAIN_ACTIVITY);
                    finish();
                    return;
                }
            }
            return;
        }
        checkPermission();
    }

    @SuppressLint("MissingPermission")
    @Override
    protected void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();


    }


    boolean isLogin = false;


    @Override
    public void onEventBus(BusEvent event) {
        super.onEventBus(event);
        if (1 == event.getActionStatus()) {
            LogsUtils.i("接口异常", event.getData());
            showToast(event.getData() + "");
            return;
        }
        if (HttpUrl.LOGIN_SMS.equals(event.getAction())) {
            showToast("验证发已发送");
            return;
        }
        if (HttpUrl.LOGIN_ONE_LOGIN.equals(event.getAction())) {
            LogsUtils.i("LOGIN_LOGIN=", event.getData());
            HdLoginBean hdLoginBean = (HdLoginBean) event.getData();
            SpSaveUtils.setToken(hdLoginBean.getToken() + "");
            if (hdLoginBean.getIs_activation() == 1) {
                SpSaveUtils.setActivation(hdLoginBean.getIs_activation() + "");
                RouterUtils.navigate(ArouterPath.PATH_APP_MAIN_ACTIVITY);
            } else {
                startActivity(AuthOrderActivity.class);
            }
            finish();
        }
    }

    LoginPresenter presenter;

    @Override
    public LoginPresenter getPresenter() {
        return presenter;
    }

    @Override
    public void intPresenter() {
        presenter = new LoginPresenter();
    }

    private boolean havePermission = false;


    private void checkPermission() {
        isLogin = false;
        //检查权限（NEED_PERMISSION）是否被授权 PackageManager.PERMISSION_GRANTED表示同意授权
        if (Build.VERSION.SDK_INT >= 30) {
            if (!Environment.isExternalStorageManager()) {
                TipUiDialog.showPermission(this, "提示",
                        "请开启文件访问权限，否则无法正常使用本应用！", v -> {
                            getSdCardPermission();
                        });
            } else {
                havePermission = true;
                getPhonePermission();
                Log.i("swyLog", "Android 11以上，当前已有权限");
            }
        } else {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    TipUiDialog.showPermission(this, "提示",
                            "请开启文件访问权限，否则无法正常使用本应用！", v -> {
                                getSdCardRwPermission();
                            });
                } else {
                    havePermission = true;
                    Log.i("swyLog", "Android 6.0以上，11以下，当前已有权限");
                    getSdCardRwPermission();
                }
            } else {
                havePermission = true;
                getPhonePermission();
                Log.i("swyLog", "Android 6.0以下，已获取权限");
            }
        }
    }


    public void getSdCardPermission() {
        XXPermissions.with(this).permission(Permission.MANAGE_EXTERNAL_STORAGE).request((permissions, all) -> {
            if (all) {
                havePermission = true;
                getPhonePermission();
            }
        });
    }

    public void getSdCardRwPermission() {
        XXPermissions.with(this).permission(Permission.WRITE_EXTERNAL_STORAGE).request((permissions, all) -> {
            if (all) {
                havePermission = true;
                getPhonePermission();
            }
        });
    }

    public void getPhonePermission() {
        XXPermissions.with(this).permission(Permission.READ_PHONE_STATE,
                Permission.READ_PHONE_NUMBERS, Permission.READ_SMS).request((permissions, all) -> {
            if (all) {
                havePermission = true;
                LogsUtils.i("测试==+authOrder");
                jPushUtils.preAuth(new JPushUtils.preAuthJpListener() {
                    @Override
                    public void onAuthStatus(boolean isStart, int code, String msg) {
                        LogsUtils.i("测试==+onAuthStatus");
                        startLogin();
                    }
                });
            }
        });
    }


    public void startLogin() {
        if (isLogin) {
            return;
        }
        isLogin = true;
        LogsUtils.i("测试==+startLogin");
//        loginBenjiYjdlTv.setText("唤起登录中...");
        jPushUtils.loginAuth(false, (isStart, code, msg) -> {
            if (code == 6000) {
                if (isStart) {
                    showLoading();
                    return;
                }
                getPresenter().getHdOneLogin(msg);
            } else if (code == 6004 || code == 604) {

            } else if (code == 6002) {
                finish();
            } else if (code == 601|| code == 6001) {
                Bundle bundle=new Bundle();
                bundle.putString("simCard","无卡");
                startActivity(LoginCodeActivity.class,bundle);
                finish();

            } else if (code == 603) {
//                loginCheckReadBox.setChecked(true);
//                loginOtherDlTv.performClick();
                if (TextUtils.isEmpty(SpSaveUtils.getToken()) || TextUtils.isEmpty(SpSaveUtils.getActivation())
                        || "0".equals(SpSaveUtils.getActivation())) {
                    startActivity(LoginCodeActivity.class);
                } else {
                    RouterUtils.navigate(ArouterPath.PATH_APP_MAIN_ACTIVITY);
                }
                finish();
            } else {
                showToast(msg);
            }
            hideLoading();
            isLogin = false;
//            loginBenjiYjdlTv.setText("一键登录");
        });
    }
}
